"""
精灵移动根据鼠标

"""

import arcade
import math

SPRITE_SCALING=0.1

WINDOW_WIDTH=200
WINDOW_HEIGHT=200
WINDOW_TITLE='SMA'

MOVEMENT_SPEED=5
ANGLE_SPEED=5


def calc_rad(p1,p2):
    """
    根据两个点，计算弧度
    """
    dx=p2[0]-p1[0]
    dy=p2[1]-p1[1]
    return math.atan2(dy,dx)

class Player(arcade.Sprite):

    def __init__(self,image,scale):
        """
        初始属性x,y,角度
        """
        super().__init__(image,scale)

        self.speed=0
        self.target=(0,0)

    def update(self,delta_time=1/60):
        # self.angle+=self.change_angle
        if self.speed==0:
            return
        
        self.rad=calc_rad((self.center_x,self.center_y),self.target)
        # print(self.rad)

        # angle_rad=math.radians(self.angle)

        self.center_x+=self.speed*math.cos(self.rad)
        self.center_y+=self.speed*math.sin(self.rad)

class GameView(arcade.View):

    def __init__(self):
        super().__init__()

        self.player_list=None

        self.player_sprite=None

        self.background_color=arcade.color.BLACK

    def setup(self):
        self.player_list=arcade.SpriteList()

        self.player_sprite=Player(":resources:images/space_shooter/playerShip1_orange.png",
                                  SPRITE_SCALING)
        self.player_sprite.center_x=WINDOW_WIDTH/2
        self.player_sprite.center_y=WINDOW_HEIGHT/2

        self.player_list.append(self.player_sprite)

    def on_draw(self):
        self.clear()
        self.player_list.draw()

    def on_update(self,delta_time):

        self.player_list.update(delta_time)

    def on_mouse_press(self, x, y,  button,modifiers):
        # 判断，如果精灵在鼠标坐标内，则不移动
        if button==arcade.MOUSE_BUTTON_LEFT:
            print(f'enter {x},{y}')
            

            # 计算鼠标坐标与精灵坐标的相对位置
            self.player_sprite.speed=MOVEMENT_SPEED
            self.player_sprite.target=(x,y)
        

    def on_mouse_release(self, x, y, button, modifiers):
        print(f'release {x},{y}')
        if button==arcade.MOUSE_BUTTON_LEFT:
            # 鼠标不再移动
            self.player_sprite.speed=0

def main():
    window=arcade.Window(WINDOW_WIDTH,WINDOW_HEIGHT,WINDOW_TITLE)

    game=GameView()
    game.setup()

    window.show_view(game)
    
    arcade.run()

if __name__=='__main__':
    main()

